package com.mall.util;


import org.springframework.context.annotation.Configuration;

import java.lang.reflect.Field;

/**
 * @author mahaoqi
 * @ClassName ColumnEdit
 * @Description TODO
 * @Date 2020/12/29 16:01
 * @Version 1.0
 **/
@Configuration
public class ColumnEdit {


    /*
     * @Author mahaoqi
     * @Description 将一个对象中存在的字段 赋给另一个对象
     * @Date 2020/12/29 16:29
     * @Param [newObject, oldObject]    newObject 从页面返回的对象   oldObject 从数据库查找的对象
     * @return java.lang.Object
     **/
    public Object updateObject(Object newObject, Object oldObject){

        try {
            // 获取对象中的所有字段
            Field[] fields = newObject.getClass().getDeclaredFields();
            //遍历
            for (int i=0;i< fields.length;i++){
                //将字段设置为可操作
                fields[i].setAccessible(true);
                //判断字段的值是否为空
                if(fields[i].get(newObject)!=null){
                    //若非空,将该值赋给  oldObject
                    fields[i].set(oldObject,fields[i].get(newObject));
                }

    //            测试
    //            System.out.println(fields[i].getName()+":"+fields[i].get(newObject));

            }
            return oldObject;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return oldObject;
    }



//    //测试
//    public static void main(String[] args){
//        Student student = new Student();
//        student.setSname("张高祥");
//        Student findStu = new Student(20172203,"张辉","123456","12356489","54564@163.cn","男");
//
//        ColumnEdit columnEdit = new ColumnEdit();
//
//        System.out.println(columnEdit.updateObject(student,findStu));
//    }
}
